package main

import (
	"flag"
	"fmt"
	"os"
	"strconv"

	"fabric-sdk/sdk"
	"fabric-sdk/server"
	"fabric-sdk/service"
)

const (
	cc_name           = "mycc"
	cc_version        = "1.0.0"
	webServerBasePort = 8080
	// FABRIC_SDK_PATH = "/home/mcloud/go/src/github.com/hyperledger/fabric-sdk/"
)

var (
	Server       sdk.Server
	channelsName = []string{"mychannel"}
	runServer    = flag.Bool("s", false, "run server") // run benchmark if false
	kafkaBroker  = flag.String("b", "127.0.0.1:9092", "kafka broker IP:port")
	kafkaTopic   = flag.String("t", "ceph", "kafka topic")
	fabricOrgID  = flag.Int("o", 1, "fabric org ID: 1-4 (default: 1)")
	objectNum    = flag.Int("n", 50000, "object number")
	configPath   = flag.String("c", "../gen_config_yaml/sdk-config-"+strconv.Itoa(*fabricOrgID)+".yaml", "config file path")
)

func main() {
	flag.Parse()

	// set sdk env info
	sdkInfos := setSdkInfo()

	// sdk setup
	sdk, err := sdk.Setup(*configPath)
	if err != nil {
		fmt.Println(">> SDK setup error:", err)
		os.Exit(-1)
	}

	// invoke chaincode set status
	fmt.Println(">> init service ... ")
	for i := 0; i < len(channelsName); i++ {
		err = sdkInfos[i].InitService(sdk, *fabricOrgID)
		if err != nil {
			fmt.Println("InitService error:", err)
			os.Exit(-1)
		}
	}

	// start chaincode event service
	fmt.Println("fabric event register ... ")
	eventService := service.EventService{
		ChaincodeID: cc_name,
	}
	for i := 0; i < len(channelsName); i++ {
		eventService.EventClient = append(eventService.EventClient, sdkInfos[i].EventClient)
	}
	go eventService.StartEventService(*kafkaBroker)
	fmt.Println("fabric event register ... done")

	// start server service
	serverInfo := server.Server{
		SdkChannelInfos: sdkInfos,
		OrgID:           *fabricOrgID,
		Port:            webServerBasePort + *fabricOrgID - 1,
		Webserver:       *runServer,
		ObjectNum:       *objectNum,
		KafkaConsumer: server.KafkaConsumer{
			KafkaNode:  *kafkaBroker,
			KafkaTopic: *kafkaTopic,
		},
	}
	server.ServerStart(serverInfo)
}

func setSdkInfo() []sdk.SdkChannelInfo {
	channelsNum := len(channelsName)
	sdkInfos := make([]sdk.SdkChannelInfo, channelsNum)
	for i := 0; i < channelsNum; i++ {
		sdkInfos[i].ChannelID = channelsName[i]
		sdkInfos[i].ChaincodeID = cc_name
		sdkInfos[i].Orgs = []*sdk.OrgInfo{
			{OrgName: "Org1", OrgUser: "User1"},
			{OrgName: "Org2", OrgUser: "User1"},
			{OrgName: "Org3", OrgUser: "User1"},
			{OrgName: "Org4", OrgUser: "User1"},
		}
	}
	return sdkInfos
}
